/**
 * 课程详情缓存助手
 * 功能：缓存百度网盘课程详情数据，减少API调用
 * 特性：使用内存缓存，30天有效期
 */

// 内存缓存存储
// 结构：{ [path]: { data: {...}, lastUpdate: timestamp } }
const courseDetailCache = {};

// 缓存有效期：30天（毫秒）
const CACHE_DURATION = 30 * 24 * 60 * 60 * 1000; // 30天

/**
 * 获取课程详情缓存
 * @param {string} coursePath - 课程路径
 * @returns {Object|null} 缓存的课程详情数据，如果不存在或已过期则返回null
 */
function getCourseDetail(coursePath) {
    const now = Date.now();
    const cache = courseDetailCache[coursePath];

    // 检查缓存是否存在且有效
    if (cache && cache.data && (now - cache.lastUpdate < CACHE_DURATION)) {
        const remainingDays = Math.floor((CACHE_DURATION - (now - cache.lastUpdate)) / (24 * 60 * 60 * 1000));
        console.log(`📦 命中缓存: ${coursePath} (剩余有效期: ${remainingDays}天)`);
        return cache.data;
    }

    // 缓存不存在或已过期
    if (cache && (now - cache.lastUpdate >= CACHE_DURATION)) {
        console.log(`⏰ 缓存已过期: ${coursePath}`);
        // 清除过期缓存
        delete courseDetailCache[coursePath];
    }

    return null;
}

/**
 * 设置课程详情缓存
 * @param {string} coursePath - 课程路径
 * @param {Object} detailData - 课程详情数据
 */
function setCourseDetail(coursePath, detailData) {
    const now = Date.now();

    courseDetailCache[coursePath] = {
        data: detailData,
        lastUpdate: now
    };

    console.log(`💾 缓存已保存: ${coursePath} (有效期: 30天)`);
}

/**
 * 清除指定课程的缓存
 * @param {string} coursePath - 课程路径，不传则清除所有缓存
 */
function clearCache(coursePath) {
    if (coursePath) {
        if (courseDetailCache[coursePath]) {
            delete courseDetailCache[coursePath];
            console.log(`🗑️  缓存已清除: ${coursePath}`);
        } else {
            console.log(`⚠️  缓存不存在: ${coursePath}`);
        }
    } else {
        // 清除所有缓存
        const count = Object.keys(courseDetailCache).length;
        Object.keys(courseDetailCache).forEach(key => {
            delete courseDetailCache[key];
        });
        console.log(`🗑️  已清除所有课程详情缓存 (${count}个)`);
    }
}

/**
 * 获取缓存统计信息
 * @returns {Object} 缓存统计信息
 */
function getCacheStats() {
    const now = Date.now();
    const stats = {
        total: 0,
        valid: 0,
        expired: 0,
        courses: []
    };

    Object.keys(courseDetailCache).forEach(path => {
        const cache = courseDetailCache[path];
        const age = now - cache.lastUpdate;
        const isExpired = age >= CACHE_DURATION;
        const remainingDays = Math.floor((CACHE_DURATION - age) / (24 * 60 * 60 * 1000));

        stats.total++;
        if (isExpired) {
            stats.expired++;
        } else {
            stats.valid++;
        }

        stats.courses.push({
            path: path,
            lastUpdate: new Date(cache.lastUpdate).toISOString(),
            remainingDays: isExpired ? 0 : remainingDays,
            isExpired: isExpired
        });
    });

    return stats;
}

/**
 * 清理过期缓存
 * @returns {number} 清理的缓存数量
 */
function cleanExpiredCache() {
    const now = Date.now();
    let cleanedCount = 0;

    Object.keys(courseDetailCache).forEach(path => {
        const cache = courseDetailCache[path];
        if (now - cache.lastUpdate >= CACHE_DURATION) {
            delete courseDetailCache[path];
            cleanedCount++;
        }
    });

    if (cleanedCount > 0) {
        console.log(`🧹 已清理 ${cleanedCount} 个过期缓存`);
    }

    return cleanedCount;
}

module.exports = {
    getCourseDetail,
    setCourseDetail,
    clearCache,
    getCacheStats,
    cleanExpiredCache
};
